#include <iostream>
using std::cout;
using std::endl;


//需求：一个类只能创建一个对象,且是唯一的对象

class Point
{
public:
    //作用：用来创建对象
    //2. 定义了一个静态的成员函数
    static Point & getInstance()
    {   //只有第一次才去执行new表达式创建对象
        //后续再调用该静态成员函数时，直接返回
        //第一次创建的对象即可
        if(nullptr == _pInstance) {
            _pInstance  = new Point();
        }
        return *_pInstance;
    }

    static void destroy()
    {
        if(_pInstance) {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }


private:
    //1. 将构造函数私有化
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
        cout << "Point(int,int)" << endl;
    }

    ~Point() {  cout << "~Point()" << endl; }
public:
    void print() const
    {
        cout << "(" << _ix
             << "," << _iy 
             << ")" << endl;
    }

private:
    int _ix;
    int _iy;
    //3. 定义一个静态的能够存储本类型对象的指针
    static Point * _pInstance;
};

Point * Point::_pInstance = nullptr;

//Point pt3(1, 1);//error

void test0()
{
    //Point pt1(1, 2);//不能让该语句编译通过
    //Point pt2(11, 12);//error
    

    Point & ref1 = Point::getInstance();
    Point & ref2 = Point::getInstance();
    ref1.print();
    ref2.print();
    cout << "&ref1:" << &ref1 << endl;
    cout << "&ref2:" << &ref2 << endl;
    
    //delete &ref1;//error 形式不够优雅, 不希望该语句编译通过
    Point::destroy();
}


int main()
{
    test0();
    return 0;
}

